package com.gobang.control;

import java.awt.Graphics;

import javax.swing.JOptionPane;

import com.gobang.model.Chessboard;
import com.gobang.util.PCPlayer;
import com.gobang.view.ChessboardPanel;
import com.gobang.view.ControlPanel;

public class Controller {
	
	private Chessboard chessboard;
	private ChessboardPanel chessboardPanel;
	private ControlPanel controlPanel;
	private PCPlayer pcPlayer;
	
	public Controller(){
		chessboard = new Chessboard(Chessboard.PIECE_BLACK);//黑棋先手
		pcPlayer = new PCPlayer(Chessboard.PIECE_WHITE, chessboard.getPieces(), chessboard);
	}
	
	public Chessboard getChessboard() {
		return chessboard;
	}
	public void setChessboard(Chessboard chessboard) {
		this.chessboard = chessboard;
	}
	public ChessboardPanel getChessboardPanel() {
		return chessboardPanel;
	}
	public void setChessboardPanel(ChessboardPanel chessboardPanel) {
		this.chessboardPanel = chessboardPanel;
	}
	public ControlPanel getControlPanel() {
		return controlPanel;
	}
	public void setControlPanel(ControlPanel controlPanel) {
		this.controlPanel = controlPanel;
	}
	
	public void drawChessboard(Graphics g){
		chessboard.drawChessboard(g);
	}
	
	public int getChessboardWidth(){
		return chessboard.getChessboardWidth();
	}
	
	public int getChessboardHeight(){
		return chessboard.getChessboardHeight();
	}
	
	public int getFrameWidth(){
		return chessboard.getChessboardWidth()+6 + 200;
	}
	
	public int getFrameHeight(){
		return chessboard.getChessboardHeight()+32;
	}
	
	public void putPiece(int x, int y){
		if( chessboard.isOver() ){
			return;
		}
		try {
			int i = (x - Chessboard.BOARD_PADDING + Chessboard.GRID_SIZE/2)/Chessboard.GRID_SIZE;
			int j = (y - Chessboard.BOARD_PADDING + Chessboard.GRID_SIZE/2)/Chessboard.GRID_SIZE;
			int result = chessboard.putChess(Chessboard.PIECE_BLACK, i, j);
			chessboardPanel.repaint();
			if(result != 0){
				if(result == Chessboard.PIECE_BLACK){
					JOptionPane.showMessageDialog(null, "恭喜您赢了");
				} else {
					JOptionPane.showMessageDialog(null, "您输了，请再接再励!");
				}
			}
			result = pcPlayer.putPiece();
			chessboardPanel.repaint();
			if(result != 0){
				if(result == Chessboard.PIECE_BLACK){
					JOptionPane.showMessageDialog(null, "恭喜您赢了");
				} else {
					JOptionPane.showMessageDialog(null, "您输了，请再接再励!");
				}
			}
		} catch (Exception e) {
		}
	}
	
	public void newGame(){
		chessboard.init(Chessboard.PIECE_BLACK);
		pcPlayer = new PCPlayer(Chessboard.PIECE_WHITE, chessboard.getPieces(), chessboard);
		chessboardPanel.repaint();
	}
}
